package com.haojiang.mh.remote.ui.frag

import android.app.Dialog
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.widget.ScrollView
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.PagerSnapHelper
import androidx.recyclerview.widget.SimpleItemAnimator
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import androidx.viewpager.widget.ViewPager
import com.google.android.material.tabs.TabLayout
import com.haojiang.mh.R
import com.haojiang.mh.cache.Const
import com.haojiang.mh.cache.MGlobal
import com.haojiang.mh.service.api.JsonCallback
import com.haojiang.mh.service.entity.*
import com.haojiang.mh.service.event.CardEvent
import com.haojiang.mh.service.event.OneEvent
import com.haojiang.mh.service.event.ReportEvent
import com.haojiang.mh.ui.adapter.MainPagerAdapter
import com.haojiang.mh.ui.adapter.OnItemChildClickListener
import com.haojiang.mh.ui.adapter.OnItemClickListener
import com.haojiang.mh.ui.adapter.ScoreUserListAdapter
import com.haojiang.mh.ui.base.BaseActivity
import com.haojiang.mh.ui.base.LazyLoadBaseFragment
import com.haojiang.mh.ui.fragment.DayFragment
import com.haojiang.mh.ui.fragment.MonthFragment
import com.haojiang.mh.ui.fragment.TwoFragment
import com.haojiang.mh.ui.fragment.WeekFragment
import com.haojiang.mh.utils.*
import com.haojiang.mh.widget.chart.SleepEvaluateCalendarView
import com.haojiang.mh.widget.scroll.ScrollableHelper
import com.haojiang.mh.widget.scroll.ScrollableLayout
import com.lzy.okgo.OkGo
import com.lzy.okgo.model.Response
import kotlinx.android.synthetic.main.frag_motor.*
import kotlinx.android.synthetic.main.frag_sleep.*
import kotlinx.android.synthetic.main.fragment_month.*
import kotlinx.android.synthetic.main.layout_time_select.*
import kotlinx.coroutines.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.File
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashMap

/**
 * 报告页
 *
 * Created by ZapFive on 2019-05-25.
 *
 * wuzhuang@mirahome.me
 */
class SleepFrag : LazyLoadBaseFragment() {

    //region 变量参数

    companion object {
        private const val PREVIOUS = -1//上一个日期单位
        private const val CURRENT = 0//当前负责刷新事件
        private const val NEXT = 1//下一个日期单位

        private const val DAY = 1
        private const val WEEK = 2
        private const val MONTH = 3
    }

    private var dayYear = -1
    private var dayMonth = -1
    private var dayDay = -1
    private var weekStartYear = -1
    private var weekStartMonth = -1
    private var weekStartDay = -1
    private var weekEndYear = -1
    private var weekEndMonth = -1
    private var weekEndDay = -1
    private var monthYear = -1
    private var monthMonth = -1
    private var selectPage = 0//DAY //0:实时 1:日报 2:周报 3:月报

    private var eventParam = HashMap<String, Any>()
    private val cardList = ArrayList<CardInfoBean>()
    private lateinit var userAdapter: ScoreUserListAdapter
    private var saveScreenshotJob: Job? = null
    private var dayStart = ""
    private var dayEnd = ""

    //endregion

    override fun getLayoutId() = R.layout.frag_sleep

    override fun initView() {
        initViewPager()
        initTabLayoutAndSwipeRefreshLayout()
        initRecyclerView()

        layout_time.visibility = View.GONE
        vp_one.currentItem = 0
//        sl_one.helper.setCurrentScrollableContainer(this)
        cir_score.setRecyclerView(rv_one)

        setSelectTitle(CURRENT)

        //保存报告图片
        aiv_save_local.setOnClickListener {
            MUtil.cancelJob(saveScreenshotJob)
            saveScreenshotJob = GlobalScope.launch {
                saveScreenshot2Local()
            }
        }
        aiv_previous.setOnClickListener { setSelectTitle(PREVIOUS) }
        aiv_next.setOnClickListener { setSelectTitle(NEXT) }
        aiv_to_top.setOnClickListener {
//            sl_one.scrollToTop()
        }
    }

    override fun onFragmentFirstVisible() {
        setSelectTitle(CURRENT)
    }

    override fun onFragmentResume() {
        super.onFragmentResume()
        val isCanOperate = SpUtil[Const.DEVICE_WIFI_MAC, ""].isNotEmpty()
        aiv_previous.isClickable = isCanOperate
        aiv_previous.alpha = if (isCanOperate) 1.0f else 0.5f
        aiv_next.isClickable = isCanOperate
        aiv_next.alpha = if (isCanOperate) 1.0f else 0.5f
    }

    override fun onFragmentPause() {
        super.onFragmentPause()
        if (srl_one.isRefreshing) {
            srl_one.isRefreshing = false
        }
    }

    override fun onDestroyView() {
        MUtil.cancelJob(saveScreenshotJob)
        super.onDestroyView()
    }

    //region initView

    private fun initViewPager() {
        srl_one.isEnabled = false
        vp_one.offscreenPageLimit = 4
        vp_one.addOnPageChangeListener(pageChangeListener)
        val fragmentList = ArrayList<Fragment>()
        fragmentList.add(TwoFragment())
        fragmentList.add(DayFragment())
        fragmentList.add(WeekFragment())
        fragmentList.add(MonthFragment())
        val titleList = ArrayList<String>()
        titleList.add(getString(R.string.title_real_time))
        titleList.add(getString(R.string.title_day))
        titleList.add(getString(R.string.title_week))
        titleList.add(getString(R.string.title_month))
        val adapter = MainPagerAdapter(childFragmentManager, fragmentList, titleList)
        vp_one.adapter = adapter
        setPageProperty(0)
    }

    private fun initTabLayoutAndSwipeRefreshLayout() {
        tl_one.setupWithViewPager(vp_one)
        tl_one.tabMode = TabLayout.MODE_FIXED
        tl_one.setSelectedTabIndicatorColor(Color.TRANSPARENT)


//        sl_one.setOnScrollListener(scrollListener)
        srl_one.setColorSchemeResources(R.color.color_golden_dark_n)
//        srl_one.setOnChildScrollUpCallback(sl_one)
        srl_one.setOnRefreshListener(refreshListener)
    }


    private fun initRecyclerView() {
        val layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
        rv_one.layoutManager = layoutManager
        rv_one.setHasFixedSize(true)
        val snapHelper = PagerSnapHelper()
        snapHelper.attachToRecyclerView(rv_one)
        userAdapter = ScoreUserListAdapter(context, cardList)
        userAdapter.setOnItemClickListener(itemClickListener)
        userAdapter.setOnItemChildClickListener(itemChildClickListener)
        rv_one.adapter = userAdapter
        val itemAnimator = rv_one.itemAnimator as SimpleItemAnimator?
        if (itemAnimator != null) {
            itemAnimator.supportsChangeAnimations = false
        }
    }

    //endregion

    //region Listener
    private val pageChangeListener = object : ViewPager.SimpleOnPageChangeListener() {
        override fun onPageSelected(position: Int) {
            //实时页面不需要显示时间
            setPageProperty(position)
//            if (!sl_one.isSticky) sl_one.scrollToTop()
            if (srl_one.isRefreshing) srl_one.isRefreshing = false
            selectPage = position
            setSelectTitle(CURRENT)
        }
    }

    private fun setPageProperty(position: Int) {
        if (position == 0) {
            layout_time.visibility = View.GONE                           //实时界面日历标题不显示
            tvTitle.visibility = View.VISIBLE                                   //实时界面实时标题显示
            srl_one.isEnabled = false                                           //下拉刷新禁用
        } else {
            layout_time.visibility = View.VISIBLE                         //实时界面日历标题显示
            tvTitle.visibility = View.INVISIBLE                              //实时界面实时标题不显示
            srl_one.isEnabled = true                                            //下拉刷新启用
        }
    }

    private val scrollListener = ScrollableLayout.OnScrollListener { currentY, _ ->
        aiv_to_top.visibility = if (currentY >= top_view.measuredHeight) View.VISIBLE else View.GONE
    }
    private val refreshListener = SwipeRefreshLayout.OnRefreshListener { setSelectTitle(CURRENT) }
    private val itemClickListener = OnItemClickListener { _, position ->
        MGlobal.instance.currLeftSide = position == 0
        setSelectTitle(CURRENT)
    }
    private val itemChildClickListener = OnItemChildClickListener { view, _, _ ->
        when (view.id) {
            R.id.aiv_mark -> {
                val layIdName = when (selectPage) {
                    DAY -> "report_day"
                    WEEK -> "report_week"
                    MONTH -> "report_month"
                    else -> return@OnItemChildClickListener
                }
                redirectExplain(layIdName)
            }
        }
    }
    //endregion

    //region 保存长截图
    private suspend fun saveScreenshot2Local() {
        /*val scrollView = scrollableView as ScrollView
        val timeBmp = ImageUtil.getBitmapByView(layout_time)
        val cardBmp = ImageUtil.getBitmapByView(rv_one)
        val chartBmp = ImageUtil.getBitmapByScrollView(scrollView)
        val mergeBmp = ImageUtil.mergeBitmap_TB(timeBmp, cardBmp, false)
        val finalBmp = ImageUtil.mergeBitmap_TB(mergeBmp, chartBmp, false)
        if (finalBmp == null) {
            withContext(Dispatchers.Main) {
                showToast(getString(R.string.toast_report_save_local_fail))
            }
        } else {
            val path =
                FileUtil.getFilePath(FileUtil.PICTURE) + "report_screenshot_" + System.currentTimeMillis() + ".jpg"
            ImageUtil.saveBitmapToFile(finalBmp, File(path))
            withContext(Dispatchers.Main) {
                showToast(getString(R.string.toast_report_save_local_success, path))
            }
        }*/
    }
    //endregion

    //region 日期相关
    private fun getDayDate(operate: Int) {
        val cal = Calendar.getInstance()
        if (operate == CURRENT && dayYear == -1 && dayMonth == -1 && dayDay == -1) {
            cal.add(Calendar.DAY_OF_MONTH, -1)
            dayYear = cal.get(Calendar.YEAR)
            dayMonth = cal.get(Calendar.MONTH) + 1
            dayDay = cal.get(Calendar.DAY_OF_MONTH)
        } else if (operate == PREVIOUS || operate == NEXT) {
            cal.set(dayYear, dayMonth - 1, dayDay)
            cal.add(Calendar.DAY_OF_MONTH, operate)
            dayYear = cal.get(Calendar.YEAR)
            dayMonth = cal.get(Calendar.MONTH) + 1
            dayDay = cal.get(Calendar.DAY_OF_MONTH)
        }
    }

    private fun isCurrentDay(): Boolean {
        val cal = Calendar.getInstance()
        val currYear = cal.get(Calendar.YEAR)
        val currMonth = cal.get(Calendar.MONTH) + 1
        val currDay = cal.get(Calendar.DAY_OF_MONTH)
        return dayYear == currYear && dayMonth == currMonth && dayDay == currDay
    }

    private fun getWeekDate(operate: Int) {
        val cal = Calendar.getInstance()
        if (operate == CURRENT && isOriginWeek()) {
            while (cal.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
                cal.add(Calendar.DAY_OF_MONTH, -1)
            }
            weekStartYear = cal.get(Calendar.YEAR)
            weekStartMonth = cal.get(Calendar.MONTH) + 1
            weekStartDay = cal.get(Calendar.DAY_OF_MONTH)
            while (cal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
                cal.add(Calendar.DAY_OF_MONTH, 1)
            }
            weekEndYear = cal.get(Calendar.YEAR)
            weekEndMonth = cal.get(Calendar.MONTH) + 1
            weekEndDay = cal.get(Calendar.DAY_OF_MONTH)
        } else if (operate == PREVIOUS || operate == NEXT) {
            cal.set(
                if (operate < 0) weekStartYear else weekEndYear,
                if (operate < 0) weekStartMonth - 1 else weekEndMonth - 1,
                if (operate < 0) weekStartDay else weekEndDay
            )
            cal.add(Calendar.DAY_OF_MONTH, operate)
            if (operate < 0) {
                weekEndYear = cal.get(Calendar.YEAR)
                weekEndMonth = cal.get(Calendar.MONTH) + 1
                weekEndDay = cal.get(Calendar.DAY_OF_MONTH)
            } else {
                weekStartYear = cal.get(Calendar.YEAR)
                weekStartMonth = cal.get(Calendar.MONTH) + 1
                weekStartDay = cal.get(Calendar.DAY_OF_MONTH)
            }
            cal.add(Calendar.DAY_OF_MONTH, operate * 6)
            if (operate < 0) {
                weekStartYear = cal.get(Calendar.YEAR)
                weekStartMonth = cal.get(Calendar.MONTH) + 1
                weekStartDay = cal.get(Calendar.DAY_OF_MONTH)
            } else {
                weekEndYear = cal.get(Calendar.YEAR)
                weekEndMonth = cal.get(Calendar.MONTH) + 1
                weekEndDay = cal.get(Calendar.DAY_OF_MONTH)
            }
        }
    }

    private fun isCurrentWeek(): Boolean {
        val cal = Calendar.getInstance()
        val currTime = cal.timeInMillis
        cal.set(weekStartYear, weekStartMonth - 1, weekStartDay, 0, 0, 0)
        val startTime = cal.timeInMillis
        cal.set(weekEndYear, weekEndMonth - 1, weekEndDay, 23, 59, 59)
        val endTime = cal.timeInMillis
        return currTime in startTime..endTime
    }

    private fun isOriginWeek(): Boolean {
        return weekStartYear == -1 && weekStartMonth == -1 && weekStartDay == -1 &&
                weekEndYear == -1 && weekEndMonth == -1 && weekEndDay == -1
    }

    private fun getMonthDate(operate: Int) {
        val cal = Calendar.getInstance()
        if (operate == CURRENT && monthYear == -1 && monthMonth == -1) {
            monthYear = cal.get(Calendar.YEAR)
            monthMonth = cal.get(Calendar.MONTH) + 1
        } else if (operate == PREVIOUS || operate == NEXT) {
            cal.set(monthYear, monthMonth - 1, 1)
            cal.add(Calendar.MONTH, operate)
            monthYear = cal.get(Calendar.YEAR)
            monthMonth = cal.get(Calendar.MONTH) + 1
        }
    }

    private fun isCurrentMonth(): Boolean {
        val cal = Calendar.getInstance()
        val currYear = cal.get(Calendar.YEAR)
        val currMonth = cal.get(Calendar.MONTH) + 1
        return currYear == monthYear && currMonth == monthMonth
    }
    //endregion

    //region 操作相关

    private fun setSelectTitle(operate: Int) {
        eventParam.clear()
        when (selectPage) {
            DAY -> {
                getDayDate(operate)
                val format = "%04d.%02d.%02d"
                tv_select_date.text =
                    String.format(Locale.getDefault(), format, dayYear, dayMonth, dayDay)
                eventParam["year"] = dayYear
                eventParam["month"] = dayMonth
                eventParam["day"] = dayDay
                EventBus.getDefault().postSticky(ReportEvent(Const.DAY_OPERATE, eventParam))
                aiv_next.isClickable = !isCurrentDay()
                aiv_next.alpha = if (isCurrentDay()) 0.5f else 1.0f
                tv_select_date.setOnClickListener {
                    showDate()
                }
            }
            WEEK -> {
                getWeekDate(operate)
                val format = "%04d.%02d.%02d - %04d.%02d.%02d"
                tv_select_date.text = String.format(
                    Locale.getDefault(),
                    format,
                    weekStartYear,
                    weekStartMonth,
                    weekStartDay,
                    weekEndYear,
                    weekEndMonth,
                    weekEndDay
                )
                eventParam["startYear"] = weekStartYear
                eventParam["startMonth"] = weekStartMonth
                eventParam["startDay"] = weekStartDay
                eventParam["endYear"] = weekEndYear
                eventParam["endMonth"] = weekEndMonth
                eventParam["endDay"] = weekEndDay
                EventBus.getDefault().postSticky(ReportEvent(Const.WEEK_OPERATE, eventParam))
                aiv_next.isClickable = !isCurrentWeek()
                aiv_next.alpha = if (isCurrentWeek()) 0.5f else 1.0f
            }
            MONTH -> {
                getMonthDate(operate)
                tv_select_date.text =
                    String.format(Locale.getDefault(), "%04d.%02d", monthYear, monthMonth)
                eventParam["year"] = monthYear
                eventParam["month"] = monthMonth
                EventBus.getDefault().postSticky(ReportEvent(Const.MONTH_OPERATE, eventParam))
                aiv_next.isClickable = !isCurrentMonth()
                aiv_next.alpha = if (isCurrentMonth()) 0.5f else 1.0f
            }
        }
    }

    fun showDate() {
        if (vp_one.currentItem != 0) {
            monthYear = dayYear
            monthMonth = dayMonth
            val year = monthYear
            val month = monthMonth
            val dayCount = MUtil.getDaysOfMonth(year, month)
            dayStart = String.format(Locale.getDefault(), "%04d-%02d-%02d", year, month, 1)
            dayEnd = String.format(Locale.getDefault(), "%04d-%02d-%02d", year, month, dayCount)
            decideToGetMonthReport()
        }

    }

    /**
     * 根据设备MAC地址和是否需要更新Token,决定去获取报告
     */
    private fun decideToGetMonthReport() {
        if (SpUtil[Const.DEVICE_WIFI_MAC, ""].isEmpty()) {
            showToast(getString(R.string.text_no_device_tip))
            context.hideLoadingDialog()
        } else {
            context.showLoadingDialog()
            if (SpUtil.isNeedGetToken()) {
//                refreshToken()
                context.refreshToken(object : BaseActivity.OnRefreshTokenSuccessListener {
                    override fun onRefreshTokenSuccess() {
                        getSelectMonthReport()
                    }

                })
            } else {
                getSelectMonthReport()
            }
        }
    }

    /**
     * 刷新Token
     */
//    private fun refreshToken() {
//        val url = Const.getToken() + SpUtil[Const.DEVICE_WIFI_MAC, ""]
//        val queryMap = HashMap<String, String>()
//        queryMap["access_key"] = Const.ACCESS_KEY
//        queryMap["secret_key"] = Const.SECRET_KEY
//        OkGo.get<TokenBean>(url).tag(this).params(queryMap).execute(object : JsonCallback<TokenBean>() {
//
//            override fun onNormalSuccess(response: Response<TokenBean>) {
//                if (response.body().error.isEmpty()) {
//                    SpUtil.put(Const.TOKEN_LOCAL, response.body().data?.token ?: "")
//                    SpUtil.put(Const.TOKEN_EXIST_TIME, System.currentTimeMillis())
//                    getSelectMonthReport()
//                } else {
//                    context.hideLoadingDialog()
//                    KLog.e("Token 更新失败 response: $response")
//                    when (response.body().error) {
//                        "key_error" -> KLog.e("公私钥错误")
//                        "mac_error" -> KLog.e("MAC地址格式错误")
//                    }
//                }
//            }
//
//            override fun onError(response: Response<TokenBean>?) {
//                context.hideLoadingDialog()
//                KLog.e("Token 更新失败 response: $response")
//            }
//        })
//    }

    /**
     * 获取月报
     */
    private fun getSelectMonthReport() {
        val url = Const.getReportList() + SpUtil[Const.DEVICE_WIFI_MAC, ""]
        val queryMap = HashMap<String, String>()
        queryMap["day_start"] = dayStart
        queryMap["day_end"] = dayEnd
        OkGo.get<PeriodReportBean>(url).tag(this).params(queryMap)
            .execute(object : JsonCallback<PeriodReportBean>() {
                override fun onNormalSuccess(response: Response<PeriodReportBean>) {
                    if (response.body().error.isEmpty()) {
                        KLog.d("数据正常") //TODO数据正常
//                    initAllChartView(response.body())
                        showMonthReportDialog(response.body())
                    } else {
                        showToast(getString(R.string.tip_get_data_fail))
                        KLog.e("getSelectMonthReport失败 response: $response")
                        when (response.body().error) {
                            "token_expired" -> KLog.e("Token 无效")
                        }
                    }
                }

                override fun onError(response: Response<PeriodReportBean>?) {
                    showToast(getString(R.string.tip_get_data_fail))
                    KLog.e("response: $response")
                }

                override fun onFinish() {
                    context.hideLoadingDialog()
                }
            })
    }

    private var mDatePickerDialog: Dialog? = null

    fun showMonthReportDialog(bean: PeriodReportBean) {
        val realList = ArrayList<SideBean>()
        if (mDatePickerDialog == null) {
            mDatePickerDialog = Dialog(context, R.style.NoAnimDialogStyle)
            mDatePickerDialog!!.setContentView(R.layout.dialog_month_report)
            mDatePickerDialog!!.setCanceledOnTouchOutside(true)
            mDatePickerDialog!!.setCancelable(true)

            val listener = View.OnClickListener { v ->
                when (v.id) {
                    R.id.aiv_next -> {
                        getMonthDate(NEXT)
                        val dayCount = MUtil.getDaysOfMonth(monthYear, monthMonth)
                        dayStart = String.format(
                            Locale.getDefault(),
                            "%04d-%02d-%02d",
                            monthYear,
                            monthMonth,
                            1
                        )
                        dayEnd =
                            String.format(
                                Locale.getDefault(),
                                "%04d-%02d-%02d",
                                monthYear,
                                monthMonth,
                                dayCount
                            )
                        decideToGetMonthReport()
                    }
                    R.id.aiv_previous -> {
                        getMonthDate(PREVIOUS)
                        val dayCount = MUtil.getDaysOfMonth(monthYear, monthMonth)
                        dayStart = String.format(
                            Locale.getDefault(),
                            "%04d-%02d-%02d",
                            monthYear,
                            monthMonth,
                            1
                        )
                        dayEnd =
                            String.format(
                                Locale.getDefault(),
                                "%04d-%02d-%02d",
                                monthYear,
                                monthMonth,
                                dayCount
                            )
                        decideToGetMonthReport()
                    }
                    R.id.v, R.id.v2, R.id.tv_select_date -> mDatePickerDialog!!.cancel()
                }
            }

            mDatePickerDialog!!.findViewById<View>(R.id.aiv_next).setOnClickListener(listener)
            mDatePickerDialog!!.findViewById<View>(R.id.tv_select_date).setOnClickListener(listener)
            mDatePickerDialog!!.findViewById<View>(R.id.aiv_previous).setOnClickListener(listener)
            mDatePickerDialog!!.findViewById<View>(R.id.v).setOnClickListener(listener)
            mDatePickerDialog!!.findViewById<View>(R.id.v2).setOnClickListener(listener)
        }

        val mSleepEvaluateCalendarView =
            mDatePickerDialog!!.findViewById<SleepEvaluateCalendarView>(R.id.sec_month_fragment)
        mSleepEvaluateCalendarView.setOnScoreBallClickListener {
            mDatePickerDialog!!.cancel()
            val eventParam = java.util.HashMap<String, Any>()
            val strings = it.split("-".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
            dayYear = Integer.parseInt(strings[0])
            dayMonth = Integer.parseInt(strings[1])
            dayDay = Integer.parseInt(strings[2])

            val format = "%04d.%02d.%02d"
            tv_select_date.text =
                String.format(Locale.getDefault(), format, dayYear, dayMonth, dayDay)
            eventParam["year"] = dayYear
            eventParam["month"] = dayMonth
            eventParam["day"] = dayDay
            EventBus.getDefault().postSticky(ReportEvent(Const.DAY_OPERATE, eventParam))
            aiv_next.isClickable = !isCurrentDay()
            aiv_next.alpha = if (isCurrentDay()) 0.5f else 1.0f
        }

        mDatePickerDialog!!.findViewById<TextView>(R.id.tv_select_date)
            .setText(String.format(Locale.getDefault(), "%04d-%02d", monthYear, monthMonth))
        mDatePickerDialog!!.findViewById<View>(R.id.aiv_next).isEnabled = !isCurrentMonth()
        mDatePickerDialog!!.findViewById<View>(R.id.aiv_next).alpha =
            if (isCurrentMonth()) 0.5f else 1.0f

        if (MGlobal.instance.currLeftSide) {//左边
            for (info in bean.data!!) {
                if (info.value.left == null) {
                    val sb = SideBean()
                    sb.report_date = info.key
                    realList.add(sb)
                } else {
                    info.value.left!!.report_date = info.key
                    realList.add(info.value.left!!)
                }
            }
        } else {
            for (info in bean.data!!) {
                if (info.value.right == null) {
                    val sb = SideBean()
                    sb.report_date = info.key
                    realList.add(sb)
                } else {
                    info.value.right!!.report_date = info.key
                    realList.add(info.value.right!!)
                }
            }
        }

        initSleepEvaluate(realList, mSleepEvaluateCalendarView)

        mDatePickerDialog!!.show()
    }

    //region 睡眠评分图表相关
    private fun initSleepEvaluate(
        beanList: List<SideBean>,
        mSleepEvaluateCalendarView: SleepEvaluateCalendarView
    ) {
        if (beanList.isNullOrEmpty()) return
        var avgDay = 0
        var avgWork = 0
        var avgWeek = 0
        var sumCount = 0//计算次数
        var bigScoreBean = SideBean()
        val tempList = ArrayList<DayScoreBean>()
        for (data in beanList) {
            val eb = DayScoreBean()
            eb.date = data.report_date
            eb.score = data.score
            tempList.add(eb)
            if (bigScoreBean.score < data.score) {
                bigScoreBean = data
            }
            if (data.score < 0) continue
            sumCount++
            avgDay += data.score
            if (MUtil.getWeek(data.report_date) in 1..5) {
                avgWork += data.score
            } else {
                avgWeek += data.score
            }
        }
        if (bigScoreBean.report_date.isNotEmpty()) {
            val day = bigScoreBean.report_date.substring(8)
            val week = MUtil.getWeekText(context, bigScoreBean.report_date)
//            tv_best_sleep_evaluate.text = String.format(Locale.getDefault(), "%1s %2s", day, week)
        } else {
//            tv_best_sleep_evaluate.text = "--"
        }
        mSleepEvaluateCalendarView.setDateAndData(tempList, bigScoreBean.report_date)
    }


    //endregion


    private fun setTargetDay(date: Map<String, Any>) {
        if (date == null) return

        dayYear = date["year"] as Int
        dayMonth = date["month"] as Int
        dayDay = date["day"] as Int
        tv_select_date.setText(
            String.format(
                Locale.getDefault(),
                "%04d.%02d.%02d",
                dayYear,
                dayMonth,
                dayDay
            )
        )
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onReceiveEvent(event: CardEvent) {
        if (event.cardList.isNullOrEmpty()) return
        cardList.clear()
        cardList.addAll(event.cardList!!)
        userAdapter.notifyDataSetChanged()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onReveiveRefreshEvent(event: OneEvent) {
        if (event.type != Const.REFRESH_DATA) return
        if (srl_one.isRefreshing) {
            srl_one.isRefreshing = false
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onReceivetToDayEvent(event: ReportEvent) {
        if (event.type != Const.DAY_SWITCH) return
        if (event.paramMap.isNullOrEmpty()) return
        setTargetDay(event.paramMap)
        vp_one.setCurrentItem(0)
    }
}